/* 
 * Graphical User Interface for Folder Flattener.
 * (c)2011-2013 Stephen J. Sarma-Weierman
 * www.iteran.com
 * 
 * This program is free software; you can redistribute it and/or
 * modify it under the terms of the GNU General Public License
 * as published by the Free Software Foundation; either version 2
 * of the License, or (at your option) any later version.
 *
 * This program is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU General Public License for more details.
 */

/*
 * FlattenerGUI.java
 *
 * Created on Sep 24, 2011, 10:45:58 AM
 */
package com.iteran.flattener;

import java.io.File;
import javax.swing.JFileChooser;
import javax.swing.JOptionPane;

/**
 *
 * @author Stephen J. Sarma-Weierman
 */
public class FlattenerGUI extends javax.swing.JFrame {

  private File targetDirectory;

  /** Creates new form FlattenerGUI */
  public FlattenerGUI() {
    initComponents();
    setLocationRelativeTo(null);
  }

  /** This method is called from within the constructor to
   * initialize the form.
   * WARNING: Do NOT modify this code. The content of this method is
   * always regenerated by the Form Editor.
   */
  @SuppressWarnings("unchecked")
    // <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents
    private void initComponents() {

        label = new javax.swing.JLabel();
        directoryField = new javax.swing.JTextField();
        browseButton = new javax.swing.JButton();
        flattenButton = new javax.swing.JButton();
        jMenuBar1 = new javax.swing.JMenuBar();
        jFileMenu = new javax.swing.JMenu();
        jQuitMenuItem = new javax.swing.JMenuItem();
        jHelpMenu = new javax.swing.JMenu();
        jAboutMenuItem = new javax.swing.JMenuItem();

        setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE);
        setResizable(false);

        label.setText("Select Directory");

        browseButton.setText("Browse");
        browseButton.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                browseButtonActionPerformed(evt);
            }
        });

        flattenButton.setText("Flatten");
        flattenButton.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                flattenButtonActionPerformed(evt);
            }
        });

        jFileMenu.setText("File");

        jQuitMenuItem.setAccelerator(javax.swing.KeyStroke.getKeyStroke(java.awt.event.KeyEvent.VK_Q, java.awt.event.InputEvent.CTRL_MASK));
        jQuitMenuItem.setText("Quit");
        jQuitMenuItem.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                jQuitMenuItemActionPerformed(evt);
            }
        });
        jFileMenu.add(jQuitMenuItem);

        jMenuBar1.add(jFileMenu);

        jHelpMenu.setText("Help");

        jAboutMenuItem.setAccelerator(javax.swing.KeyStroke.getKeyStroke(java.awt.event.KeyEvent.VK_F1, 0));
        jAboutMenuItem.setText("About");
        jAboutMenuItem.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                jAboutMenuItemActionPerformed(evt);
            }
        });
        jHelpMenu.add(jAboutMenuItem);

        jMenuBar1.add(jHelpMenu);

        setJMenuBar(jMenuBar1);

        javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
        getContentPane().setLayout(layout);
        layout.setHorizontalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addContainerGap()
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addComponent(flattenButton, javax.swing.GroupLayout.DEFAULT_SIZE, 376, Short.MAX_VALUE)
                    .addComponent(label)
                    .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, layout.createSequentialGroup()
                        .addComponent(directoryField, javax.swing.GroupLayout.DEFAULT_SIZE, 316, Short.MAX_VALUE)
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                        .addComponent(browseButton)))
                .addContainerGap())
        );
        layout.setVerticalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addContainerGap()
                .addComponent(label)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(directoryField, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                    .addComponent(browseButton))
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addComponent(flattenButton)
                .addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
        );

        pack();
    }// </editor-fold>//GEN-END:initComponents

    private void browseButtonActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_browseButtonActionPerformed
      JFileChooser fileChooser = new JFileChooser();
      fileChooser.setFileSelectionMode(JFileChooser.DIRECTORIES_ONLY);
      if (directoryField.getText() != null
              && !directoryField.getText().equals("")) {
        fileChooser.setCurrentDirectory(new File(directoryField.getText()));
      }
      int returnVal = fileChooser.showDialog(null, "Select");
      if (returnVal == JFileChooser.APPROVE_OPTION) {
        directoryField.setText(fileChooser.getSelectedFile().getAbsolutePath());
      }
    }//GEN-LAST:event_browseButtonActionPerformed

    private void flattenButtonActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_flattenButtonActionPerformed
      File dir = new File(directoryField.getText());
      if (!dir.exists()) {
        JOptionPane.showMessageDialog(this,
                "Unable to locate directory " + dir.getName());
      } else if (!dir.isDirectory()) {
        JOptionPane.showMessageDialog(this,
                dir.getName() + " is not a directory");
      } else {
        targetDirectory = dir;
        int confirm = JOptionPane.showConfirmDialog(this, 
                "Are you sure you want to flatten " + targetDirectory
                + "?\nTHERE IS NO WAY TO UNDO THIS ACTION.");
        if (confirm == 0) {
          boolean success = flatten(dir);
          if (success) {
            JOptionPane.showMessageDialog(this, "Success!");
          }
        } else {
            JOptionPane.showMessageDialog(this, "Action cancelled.");
        }
        directoryField.setText("");
      }
    }//GEN-LAST:event_flattenButtonActionPerformed

    private void jQuitMenuItemActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jQuitMenuItemActionPerformed
      System.exit(0);
    }//GEN-LAST:event_jQuitMenuItemActionPerformed

    private void jAboutMenuItemActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jAboutMenuItemActionPerformed
      AboutDialog about = AboutDialog.getInstance();
      about.setLocationRelativeTo(this);
      about.setVisible(true);
    }//GEN-LAST:event_jAboutMenuItemActionPerformed

  private boolean flatten(File curr) {
    if (!curr.canWrite()) {
      JOptionPane.showMessageDialog(this,
              "You do not have write permissions for " 
              + curr.getAbsolutePath());
      return false;
    } else {
      boolean successful = true;
      File[] files = curr.listFiles();
      for (File file : files) {
        if (file.isDirectory()) {
          if (!flatten(file))
            successful=false;
          if (!file.delete()) {
            JOptionPane.showMessageDialog(this,
              "Unable to delete directory " + file.getAbsolutePath());
            successful = false;
          }
            
        } else if (file.getName().equals("desktop.ini")) {
          file.delete();
        } else if (!curr.equals(targetDirectory)) {
          File tFile = new File(targetDirectory, file.getName());
          if (tFile.exists()) {
            String newFileName =
                    JOptionPane.showInputDialog("Duplicate file. "
                    + "Enter new filename for " + file.getAbsolutePath(),
                    file.getName());
            tFile = new File(targetDirectory, newFileName);
          }
          if (!file.renameTo(tFile)) {
            JOptionPane.showMessageDialog(this,
              "Unable to move file " + file.getAbsolutePath());
            successful = false;
          }
        }
      }
      return successful;
    }
  }

  /**
   * @param args the command line arguments
   */
  public static void main(String args[]) {
    /* Set the Nimbus look and feel */
    //<editor-fold defaultstate="collapsed" desc=" Look and feel setting code (optional) ">
        /* If Nimbus (introduced in Java SE 6) is not available, stay with the default look and feel.
     * For details see http://download.oracle.com/javase/tutorial/uiswing/lookandfeel/plaf.html 
     */
    try {
      for (javax.swing.UIManager.LookAndFeelInfo info : javax.swing.UIManager.getInstalledLookAndFeels()) {
        if ("Nimbus".equals(info.getName())) {
          javax.swing.UIManager.setLookAndFeel(info.getClassName());
          break;
        }
      }
    } catch (ClassNotFoundException ex) {
      java.util.logging.Logger.getLogger(FlattenerGUI.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
    } catch (InstantiationException ex) {
      java.util.logging.Logger.getLogger(FlattenerGUI.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
    } catch (IllegalAccessException ex) {
      java.util.logging.Logger.getLogger(FlattenerGUI.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
    } catch (javax.swing.UnsupportedLookAndFeelException ex) {
      java.util.logging.Logger.getLogger(FlattenerGUI.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
    }
    //</editor-fold>

    /* Create and display the form */
    java.awt.EventQueue.invokeLater(new Runnable() {

      public void run() {
        new FlattenerGUI().setVisible(true);
      }
    });
  }
    // Variables declaration - do not modify//GEN-BEGIN:variables
    private javax.swing.JButton browseButton;
    private javax.swing.JTextField directoryField;
    private javax.swing.JButton flattenButton;
    private javax.swing.JMenuItem jAboutMenuItem;
    private javax.swing.JMenu jFileMenu;
    private javax.swing.JMenu jHelpMenu;
    private javax.swing.JMenuBar jMenuBar1;
    private javax.swing.JMenuItem jQuitMenuItem;
    private javax.swing.JLabel label;
    // End of variables declaration//GEN-END:variables
}
